package com.zone.gateway.core.socket.agreement;

import com.zone.gateway.core.socket.agreement.impl.GetParser;
import com.zone.gateway.core.socket.agreement.impl.PostFormDataParser;
import com.zone.gateway.core.socket.agreement.impl.PostJsonParser;
import io.netty.handler.codec.http.*;

/**
 * @author: zongzi
 * @description: 请求解析器指导者，用于获取解析器
 * @date: 2025/4/22
 */
public class RequestParserDirector {
    private FullHttpRequest fullHttpRequest;

    public RequestParserDirector(FullHttpRequest fullHttpRequest) {
        this.fullHttpRequest = fullHttpRequest;
    }

    public IRequestParser getParser() {
        HttpMethod method = fullHttpRequest.method();
        if (HttpMethod.GET.equals(method)) {
            return new GetParser();
        }
        if (HttpMethod.POST.equals(method)) {
            HttpHeaders headers = fullHttpRequest.headers();
            String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
            if (HttpHeaderValues.APPLICATION_JSON.toString().equals(contentType)) {
                return new PostJsonParser();
            }
            if (HttpHeaderValues.MULTIPART_FORM_DATA.toString().equals(contentType)) {
                return new PostFormDataParser();
            }
        }
        throw new RuntimeException("not found request parser");
    }

    public String getUri() {
        // 解析uri， 如：/getxxx?key=value&key2=value2
        String uri = fullHttpRequest.getUri();
        int endIndex = uri.indexOf("?");
        return endIndex > 0 ? uri.substring(0, endIndex) : uri;
    }
}
